################################################################################
# Find frequency count of all elements
################################################################################

use strict;
use File::Find;



#All files will be stored in subfolders in this directory.
my $baseDirectory = "C:/Documents and Settings/hellerja/Desktop/temp/Kiva/";
my $loanDirectory = $baseDirectory."xml/loans/";

my %elementCount;

#find(\&findElements, $loanDirectory);
#find(\&findElements, $baseDirectory."xml/partners.xml");
find(\&findElements, "D:/Kiva/kiva_ds_xml/loans/166.xml");


#Print elements and their frequency count, sorted by number
foreach my $value (sort {$elementCount{$a} <=> $elementCount{$b} } keys %elementCount)
{
  print "$value $elementCount{$value}\n";
}



################################################################################
sub findElements
{
  my $fileName = $_;

  #Process any files that end in .xml
  if (lc($fileName) =~ /.*\.xml$/)
  #if (lc($fileName) =~ /^84.xml$/)
  {
    #print $fileName."\n";
    open FILE, "<", $fileName or die $!;
    
    while (my $line = <FILE>)
    {
      #Get everything between the opening tag, up to the first word boundary
      $_ = $line;
      while ( m/<(\w*)\b/g )
      {
        $elementCount{$1} = $elementCount{$1}+1;
        #print $1."\n";
      }
    }
  }
}
